package 多线程篇;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class 线程池demo {
    // 1、新建线程池对象
    public  static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
            60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(50), new ThreadPoolExecutor.CallerRunsPolicy());
    public static void main(String[] args) {


        // 2、新建临时存储List获取线程防火的future对象。等线程执行完毕再拿数据，防止线程阻塞。
        List<Future<String>> tempList = new ArrayList<>();

        // 3、模拟线程池执行
        for (int i = 0; i < 5; i++) {
            // 线程池执行主要靠这个submit
            Future<String> submit = poolExecutor.submit(new CallableDemo(i));
            // 我们步骤 2 构造的List 就发生作用了。
            tempList.add(submit);
        }

        // 最后一定要记得 shutdown 线程池 不然他就一直无限等待阻塞。
        poolExecutor.shutdown();

        // 做一个死循环判断线程池是否shutdown
        while (true) {
            if (poolExecutor.isTerminated()) {
                System.out.println("线程结束了");
                break;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 然后就是拿出线程池返回的数据了
        for (Future<String> stringFuture : tempList) {
            try {
                System.out.println(stringFuture.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

    }
}
class CallableDemo implements java.util.concurrent.Callable<String> {
    List<String> tempList = new ArrayList<>();
    Integer i;

    CallableDemo(Integer i) {
        this.i = i;
    }


    @Override
    public String call() throws Exception {
        return getCurrentThreadName(i);
    }


    public String getCurrentThreadName(Integer i) {
        System.out.println(i);
        return Thread.currentThread().getName() + i;
    }
}